<template>
  <div class="group-side-bar">
    <!-- 群聊信息 -->
    <div class="flex flex-ct bd-bottom pb-10">
      <div class="flex flex-center mr-10">
        <BaseImage
          class="kang-avatar large"
          :class="isQunzhu ? 'hover click' : ''"
          :src="props.info?.conversation?._target?.portrait"
          @click="
            () => {
              if (isQunzhu) {
                elBaseUpload?.elFile?.click()
              }
            }
          "
        ></BaseImage>

        <BaseUpload
          ref="elBaseUpload"
          @success="onAvatarUploadSuccess"
        ></BaseUpload>
      </div>

      <div class="flex-1">
        <div class="fz-18 hide-1">
          {{ props.info?.conversation?._target?.name }}
        </div>
        <div class="flex flex-cc mb-5">
          <div class="flex-1 mr-10">
            <n-input
              ref="elInput"
              class="kang-input--normal"
              placeholder="备注"
              :disabled="!isEdit"
              @blur="updateGroupRemark"
              @keydown.enter="updateGroupRemark"
              v-model:value="props.info.conversation._target.remark"
            ></n-input>
          </div>
          <div
            class="flex flex-center click hover"
            @click="startEdit"
            v-if="!isEdit"
          >
            <img style="width: 16px" src="@/kang/img/icon_edit.png" />
          </div>
        </div>
        <div class="fz-12 cl-basic">群聊的备注仅自己可见</div>
      </div>
    </div>

    <!-- 开关 -->
    <div class="bd-bottom pt-10 pb-10">
      <div class="switch flex flex-cc flex-rb">
        <div class="flex flex-cc">
          <div class="icon flex flex-cc">
            <img style="width: 16px" src="@/kang/img/icon_lu.png" />
          </div>
          <div>保存到通讯录</div>
        </div>

        <div>
          <n-switch
            :default-value="props.info.conversation._target._isFav"
            @update:value="setFavGroup"
          ></n-switch>
        </div>
      </div>

      <div class="switch flex flex-cc flex-rb">
        <div class="flex flex-cc">
          <div class="icon flex flex-cc">
            <img
              style="width: 24px; transform: translateX(-4px)"
              src="@/kang/img/icon_user_notice.png"
            />
          </div>
          <div>消息免打扰</div>
        </div>

        <div>
          <n-switch
            :default-value="props.info.isSilent"
            @update:value="setConversationSilent"
          ></n-switch>
        </div>
      </div>

      <div class="switch flex flex-cc flex-rb">
        <div class="flex flex-cc">
          <div class="icon flex flex-cc">
            <img
              style="width: 24px; transform: translateX(-4px)"
              src="@/kang/img/icon_user_fixed.png"
            />
          </div>
          <div>聊天置顶</div>
        </div>

        <div>
          <n-switch
            :checked-value="1"
            :unchecked-value="0"
            :default-value="props.info.top"
            @update:value="setConversationTop"
          ></n-switch>
        </div>
      </div>
    </div>

    <!-- 群成员 -->
    <div>
      <div class="flex flex-cc mt-10 mb-10">
        <div class="fz-16 mr-10">群成员</div>

        <!-- 添加成员 -->
        <div
          class="flex flex-center click hover mr-10"
          @click="showSelectUserDialog('add')"
          v-if="isQunzhu"
        >
          <img style="width: 18px" src="@/kang/img/icon_group_add.png" />
        </div>

        <!-- 移除成员 -->
        <div
          class="flex flex-center click hover"
          @click="showSelectUserDialog('remove')"
          v-if="isQunzhu"
        >
          <img style="width: 18px" src="@/kang/img/icon_group_remove.png" />
        </div>
      </div>

      <!-- 搜索框 -->
      <div class="search mb-10">
        <n-input type="text" placeholder="搜索" v-model:value="keyword">
          <template #prefix>
            <n-icon size="20">
              <SearchOutline></SearchOutline>
            </n-icon>
          </template>
        </n-input>
      </div>

      <!-- 成员列表 -->
      <ScrollView style="height: 360px">
        <div class="result">
          <ul>
            <li
              class="friend flex flex-cc"
              v-for="(v, i) in showMemberList"
              :key="i"
            >
              <div class="mr-10">
                <BaseImage class="kang-avatar" :src="v.portrait"></BaseImage>
              </div>

              <div class="flex-1">{{ v.displayName || v.name }}</div>
            </li>
          </ul>
        </div>
      </ScrollView>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { SearchOutline } from '@vicons/ionicons5'
import store from '@/store'
import api from '@/kang/js/api'
import mitt from '@/kang/js/mitt'
import wfc from '@/wfc/client/wfc'
import EventType from '@/wfc/client/wfcEvent'
import ModifyGroupInfoType from '@/wfc/model/modifyGroupInfoType'
import { checkIsQunzhu } from './utils'

const props = defineProps({
  // 当前会话信息
  info: {
    type: Object,
    default: {},
  },
})

const elInput = ref(null)
const elBaseUpload = ref(null)
const keyword = ref('')
const isEdit = ref(null)
const selectUserConfig = ref({})

const memberList = ref([])

const showMemberList = computed(() => {
  if (keyword.value.trim()) {
    return memberList.value.filter((v) => {
      let name = v.displayName || v.userName
      let count = 0

      name.split('').map((w) => {
        if (keyword.value.includes(w)) {
          count += 1
        }
      })

      return count > 0
    })
  } else {
    return memberList.value
  }
})

// 群Id
const groupId = computed(() => {
  return props.info.target
})

// 是否是群主
const isQunzhu = checkIsQunzhu(groupId.value)

// 好友列表
const friendList = computed(() => {
  const list = store.state.contact.favContactList.concat(
    store.state.contact.friendList
  )

  let ids = memberList.value.map((v) => v.uid)

  list.forEach((v) => {
    if (ids.includes(v.uid)) {
      v.disabled = true
    } else {
      v.disabled = false
    }
  })

  return list
})

onMounted(() => {
  onMemberListUpdate()
  wfc.eventEmitter.on(EventType.UserInfosUpdate, onMemberListUpdate)
  wfc.eventEmitter.on(EventType.GroupMembersUpdate, onMemberListUpdate)
})

onBeforeUnmount(() => {
  wfc.eventEmitter.removeListener(EventType.UserInfosUpdate, onMemberListUpdate)
  wfc.eventEmitter.removeListener(
    EventType.GroupMembersUpdate,
    onMemberListUpdate
  )
})

// 添加成员
async function addGroupMember({ selectedUserList }) {
  try {
    const params = {
      groupId: groupId.value,
      members: selectedUserList.map((v) => {
        return {
          memberId: v.id,
        }
      }),
    }

    selectUserConfig.value.loading = true
    const { code } = await api.addGroupMember(params)
    selectUserConfig.value.loading = false

    if (code === 200) {
      $message.success('添加成功')
      selectUserConfig.value.visible = false
    }
  } catch (err) {
    console.log(err)
    selectUserConfig.value.loading = false
  }
}

// 移除成员
async function removeGroupMember({ selectedUserList }) {
  try {
    const params = {
      groupId: groupId.value,
      members: selectedUserList.map((v) => v.id),
    }

    selectUserConfig.value.loading = true
    const { code } = await api.removeGroupMember(params)
    selectUserConfig.value.loading = false

    if (code === 200) {
      $message.success('移除成功')
      selectUserConfig.value.visible = false
    }
  } catch (err) {
    console.log(err)
    selectUserConfig.value.loading = false
  }
}

// 设置群头像
function onAvatarUploadSuccess({ url }) {
  wfc.modifyGroupInfo(
    groupId.value,
    ModifyGroupInfoType.Modify_Group_Portrait,
    url,
    [],
    null,
    () => {
      $message.success('修改成功')
    },
    (err) => {
      console.error(err)
      $message.error('修改失败')
    }
  )
}

// 设置群备注
function updateGroupRemark() {
  isEdit.value = false

  wfc.setGroupRemark(
    groupId.value,
    props.info.conversation._target.remark,
    () => {
      wfc.updateConversationInfo(props.info.conversation)
    },
    (err) => {
      console.error(err)
    }
  )
}

function startEdit() {
  isEdit.value = true
  setTimeout(() => {
    elInput.value?.focus()
  }, 0)
}

// 保存到通讯录
function setFavGroup(_isFav) {
  wfc.setFavGroup(groupId.value, _isFav, props.info.conversation, () => {
    store.reloadFavGroupList()
  })
}

// 消息免打扰
function setConversationSilent(isSilent) {
  store.setConversationSilent(props.info.conversation, isSilent)
}

// 聊天置顶
function setConversationTop(top) {
  store.setConversationTop(props.info.conversation, top ? 1 : 0)
}

function onMemberListUpdate() {
  memberList.value = store.getConversationMemberUsrInfos(
    props.info.conversation
  )
}

function showSelectUserDialog(type = 'add') {
  if (type === 'add') {
    selectUserConfig.value = {
      title: '添加成员',
      submitBtnText: '确认添加',
      list: friendList.value.map((v) => {
        return {
          id: v.uid,
          avatar: v.portrait,
          name: v.displayName || v.userName,
          disabled: v.disabled,
          isSelected: v.disabled ? true : false,
        }
      }),
      visible: true,
      loading: false,
      onSubmit: (e) => addGroupMember(e),
    }
  } else {
    selectUserConfig.value = {
      title: '移除成员',
      submitBtnText: '确认移除',
      list: memberList.value
        .filter((v) => v.uid != wfc.getUserId())
        .map((v) => {
          return {
            id: v.uid,
            avatar: v.portrait,
            name: v.displayName || v.userName,
            isSelected: false,
          }
        }),
      visible: true,
      loading: false,
      onSubmit: (e) => removeGroupMember(e),
    }
  }

  mitt.emit('dialog:selectUser', selectUserConfig.value)
}
</script>

<style lang="scss" scoped>
.group-side-bar {
  .search {
    :deep(.n-input) {
      background-color: var(--color-bg);
      border-radius: 10px;

      .n-input__border {
        display: none;
      }
    }
  }

  .switch {
    &:not(:last-child) {
      margin-bottom: 10px;
    }

    .icon {
      width: 30px;
    }
  }

  .result {
    .friend {
      padding: 10px;

      &:hover {
        background-color: var(--color-bg);
      }
    }
  }
}
</style>
